package com.wujiming.music;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.fluent.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 武继明 [wzslw@163.com]
 * @since 16-12-1 下午1:44
 */
@Service
public class QQMusicSearchServiceImpl implements MusicSearchService {
    private static final Logger LOGGER= LoggerFactory.getLogger(QQMusicSearchServiceImpl.class);
    private static final String API="https://c.y.qq.com/soso/fcgi-bin/search_cp?jsonpCallback=cb&w={w}&p={p}&n={n}";

    @Override
    public Page<Song> search(String key,Integer page,Integer size) {
        String url=API.replace("{w}",key).replace("{p}",page.toString()).replace("{n}",size.toString());
        String s = request(url);
        return parse(s);
    }

    private String request(String url) {
        String s = null;
        try {
            s = Request.Get(url)
                    .userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.100 Safari/537.36")
                    .execute()
                    .returnContent().asString();
        } catch (IOException e) {
            LOGGER.error("搜索异常:{}",e);
        }
        return s;
    }

    private Page<Song> parse(String s) {
        final JSONObject jsonObject = JSON.parseObject(s.substring(3, s.length() - 1));
        final JSONObject songJson = jsonObject.getJSONObject("data").getJSONObject("song");
        final Integer totalnum = songJson.getInteger("totalnum");
        final Integer curpage = songJson.getInteger("curpage");
        final Integer curnum = songJson.getInteger("curnum");
        final JSONArray songList = songJson.getJSONArray("list");
        final List<Song> songSet = songList.stream().map(o -> {
            JSONObject jo = (JSONObject) o;
            final List<String> singerNames= jo.getJSONArray("singer").stream().map(o1 -> {
                JSONObject jo1 = (JSONObject) o1;
                return jo1.getString("name");
            }).collect(Collectors.toList());
            final Song song = new Song(jo.getString("songname"), StringUtils.collectionToDelimitedString(singerNames,"/"), null);
            song.setData(String.valueOf(jo.get("songid")));
            return song;
        }).collect(Collectors.toList());
        return new PageImpl<>(songSet,new PageRequest(curpage,curnum),totalnum);
    }
}
